package com.newzqxq.common.utils;

import com.alibaba.fastjson.JSON;
import com.newzqxq.common.constant.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
  * @Title  实体转化工具类
  * @Author 向问天 xwt@newzqxq.com
  * @Date  2017-12-06 10:05
  * @Desc
 **/
public class SimpleBeanUtils {

    private static Logger logger = LoggerFactory.getLogger(SimpleBeanUtils.class);

    /**
     * 解析Result中data,适用于传递单个实体
     * @param re Result对象
     * @param errMsg 错误提示
     * @param isAllowNull 是否允许data为空 true=允许
     * @param tClass 实体类class
     * @param <T>
     * @return
     */
    public static <T> T parseDataFromResult(Result re, String errMsg, boolean isAllowNull, Class<? extends T> tClass) {
        if (re == null || re.getCode()!=0) {
            logger.error("parseDataFromResult:{}", re);
            throw new RuntimeException("调用" + errMsg + "失败！");
        }
        if (!isAllowNull && re.getData() == null) {
            throw new RuntimeException(errMsg + "为空");
        }
        if (re.getData() instanceof Map) {
            return getInstance((Map) re.getData(), tClass);
        }
        return (T) re.getData();
    }

    /**
     * 解析List,将map列表转换为实体类列表
     * @param list List对象
     * @param tClass 实体类class
     * @param <T>
     * @return
     */
    public static <T> List<T> parseDataList(List list, Class<? extends T> tClass) {
        List<T> reList = new ArrayList<T>();
        if (list == null || list.isEmpty()) {
            return reList;
        }
        if (list.get(0) instanceof Map) {
            for (int i=0; i< list.size(); i++) {
                reList.add(getInstance((Map) list.get(i), tClass));
            }
            return reList;
        }
        return list;
    }

    public static <T> T getInstance(Map map, Class<? extends T> tClass) {
        return JSON.parseObject(JSON.toJSONString(map), tClass);
    }
}
